package drds.common.db.sql_mapping.configuration;


import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;

import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


public class ResultMap {


    @Setter
    @Getter
    private Class<?> resultMapClass;
    @Setter
    @Getter
    private List<ResultMapping> resultMappingList = new ArrayList<ResultMapping>();
    //
    @Setter
    @Getter
    private Set<String> columnNameSet = new HashSet<>();
    @Setter
    @Getter
    private Set<String> propertyNameSet = new HashSet<>();
    @Setter
    @Getter
    private ConcurrentHashMap propertyNameToColumnNameMap = new ConcurrentHashMap<String, String>();
    @Setter
    @Getter
    private ConcurrentHashMap columnNameMapToPropertyNameMap = new ConcurrentHashMap<String, String>();

    //
    public List<ResultMapping> copyResultMappingList() {
        List<ResultMapping> resultMappingList = new ArrayList<ResultMapping>();
        if (this.resultMappingList != null) {
            for (ResultMapping resultMapping : this.resultMappingList) {
                resultMappingList.add(resultMapping.copy());
            }
        }
        return resultMappingList;
    }

    //map绑定为dto
    public Object bind(@NonNull Map<String, Object> map) {
        try {
            Object object = resultMapClass.newInstance();
            for (ResultMapping resultMapping : resultMappingList) {
                Object value = map.get(resultMapping.getColumnName());
                Field field = resultMapClass.getDeclaredField(resultMapping.getPropertyName());
                field.setAccessible(true);
                field.set(object, value);
            }
            return object;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("字段缺少");
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
